package module.library.service.impl;

import common.util.DBUtil;
import dao.LibraryDao.BookItemDao;
import dao.LibraryDao.BorrowDao;
import dao.impl.LibraryDaoImpl.BookItemDaoImpl;
import dao.impl.LibraryDaoImpl.BorrowDaoImpl;
import common.model.Entity.libraryEntity.Borrow;
import common.model.Entity.libraryEntity.enums.BookStatus;
import common.model.Entity.libraryEntity.enums.BorrowStatus;
import common.model.Entity.libraryEntity.BookItem;
import common.model.Entity.libraryEntity.BorrowingRules;


import module.library.service.BorrowService;
import network.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * BorrowService 接口的实现类
 */
public class BorrowServiceImpl implements BorrowService {
    private static final Logger logger = LoggerFactory.getLogger(BorrowServiceImpl.class);

    // 实例化 DAO，遵循 StudentServiceImpl 的模式
    private final BorrowDao borrowDao = new BorrowDaoImpl();
    private final BookItemDao bookItemDao = new BookItemDaoImpl();

    // 私有静态常量实例，类加载时初始化
    private static final BorrowService INSTANCE = new BorrowServiceImpl();

    // 私有构造方法，防止外部创建实例
    private BorrowServiceImpl() {}

    // 公开的静态获取方法，提供全局访问点
    public static BorrowService getInstance() {
        return INSTANCE;
    }

    @Override
    public Response<?> borrowBook(Long itemId,Long userId) {
        Borrow borrow = new Borrow();
        borrow.setItemId(itemId);
        borrow.setUserId(userId);
        borrowDao.save(borrow);
        return Response.success();
    }

    @Override
    public Response<?> returnBook(Long itemId,Long userId) {
        Borrow borrow = new Borrow();
        borrow.setItemId(itemId);
        borrow.setUserId(userId);
        borrowDao.save(borrow);
        return Response.success();
    }

    /**
     * 获取用户所有未归还的图书借阅记录 需要加载到前端的用户借阅记录中
     * @param userId 用户ID。
     * @return 该用户所有未归还的图书列表。
     */
    @Override
    public Response<List<Borrow>> findActiveBorrowByUser(Long userId) {
        List<Borrow> list = borrowDao.findActiveBorrowByUser(userId);
        return Response.success(list);
    }

    /**
     * 根据借阅记录ID获取详情。
     * @param id 借阅记录ID。
     * @return 匹配的借阅记录，如果未找到则返回 Optional.empty()。
     */
    @Override
    public Response<Optional<Borrow>> findById(Long id) {
        Optional<Borrow> borrowOptional = borrowDao.findById(id);
        if (borrowOptional.isEmpty()) {
            return Response.error("未找到该借阅记录");
        }
        return Response.success(borrowOptional);
    }

}
